package cn.jbolt.ai.core.chain.node.action.intention;

import cn.hutool.core.util.StrUtil;
import cn.jbolt.ai.core.chain.node.base.AppConfigConstant;
import cn.jbolt.ai.core.chain.node.action.funccall.FuncCallNodeProvider;
import cn.jbolt.ai.core.chain.node.base.LlmConfig;
import cn.jbolt.ai.app.service.AiAppService;
import cn.jbolt.ai.core.chain.ChainContext;
import cn.jbolt.ai.core.chain.node.base.BaseNode;
import cn.jbolt.ai.core.chain.node.provider.IntentionNodeProvider;
import com.fasterxml.jackson.databind.JsonNode;
import com.jboltai.capability.message.AIIntention;
import com.jboltai.capability.model.JBoltAI;
import com.jboltai.event.ai.aiintention.AIIntentionEvent;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
public class DefaultIntentionNodeProvider extends BaseNode implements IntentionNodeProvider {
    private static final Logger logger = LoggerFactory.getLogger(FuncCallNodeProvider.class);
    @Autowired
    private AiAppService aiAppService;

    @Override
    public AIIntention provide(JsonNode nodeConfig, ChainContext context) {
        IntentionNodeConfig intentionConfig = IntentionNodeConfig.from(nodeConfig.get(AppConfigConstant.CONFIG_TYPE_INTENTION));
        LlmConfig llmConfig = LlmConfig.from(nodeConfig.get(AppConfigConstant.CONFIG_TYPE_LLM));

        if (intentionConfig.getIntentions() == null || intentionConfig.getIntentions().length == 0) {

            throw new RuntimeException("未绑定意图");
        }

        if (StrUtil.isBlank(intentionConfig.getInputField())) {
            throw new RuntimeException("未配置意图输入字段");
        }

        String prompt = context.getAttr(intentionConfig.getInputField());
        if (prompt == null) {
            throw new RuntimeException("意图输入字段未绑定数据");
        }

        AIIntentionEvent event = JBoltAI.recognizeIntention(prompt, intentionConfig.getIntentions());


        //根据配置初始化event
        super.configLlm(llmConfig, context, event);
        //configLlm 会覆盖prompt，所以这里要重新设置一下
        event.prompt(prompt);
        AIIntention intention = event.get();


        if (StrUtil.isNotBlank(intentionConfig.getOutputField())) {
            context.setAttr(intentionConfig.getOutputField(), intention);
        }

        return intention;

    }






}
